package com.jzoom.zoom.admin.models;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;

import org.beetl.core.Configuration;
import org.beetl.core.ErrorHandler;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.resource.StringTemplateResourceLoader;

import com.jzoom.zoom.admin.entities.DecoTableVo;
import com.jzoom.zoom.admin.entities.DecoTableVo.DecoColumn;
import com.jzoom.zoom.common.json.JSON;
import com.jzoom.zoom.dao.Record;
import com.jzoom.zoom.common.annotations.Inject;

/**
 * 生成页面服务
 * 
 * @author jzoom
 *
 */
public class GenerateService {
	public GroupTemplate group;
	@Inject
	private DecorationTableService tableModel;

	public GenerateService() {
		StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
		try {
			group = new GroupTemplate(resourceLoader, Configuration.defaultConfiguration());
			final ErrorHandler oldErrorHandler = group.getErrorHandler();
			group.setErrorHandler(new ErrorHandler() {
				
				@Override
				public void processExcption(BeetlException beeExceptionos, Writer writer) {
					oldErrorHandler.processExcption(beeExceptionos, writer);
					throw new RuntimeException(beeExceptionos);
				}
			});
		} catch (IOException e) {
			throw new RuntimeException("创建模板对象失败", e);
		}
	}

	void fixData(DecoTableVo data) {
		// fixData
		for (DecoColumn column : data.getColumns()) {
			if (column.getComment() != null) {
				column.setComment(column.getComment().replace("\"", "\\\""));
			}
		}
		if (data.getComment() != null) {
			data.setComment(data.getComment().replace("\"", "\\\""));
		}
	}

	@SuppressWarnings("unchecked")
	public void generatePage(String templateGroup, String ds, String table) {
		// 查询一下template是否存在
		List<Record> list = tableModel.getTempltesByTemplateGroupName(templateGroup);
		DecoTableVo data = tableModel.getTable(ds, table);
		fixData(data);
		
		for (Record record : list) {
			Map<String, Object> map = JSON.parse(JSON.stringify(data), Map.class);
			map.put("primaryKey", data.getPrimaryKey());
			record.put("ds", ds);
			record.put("table", table);

			// 插入记录
			String url = render(record.getString("url"), record);
			String content = render(record.getString("content"), map);
			tableModel.insertOrUpdate(url,content );
		}
	}

	public String render(String content, Map<String, Object> data) {
		Template t = group.getTemplate(content);
		t.binding(data);
		return t.render();
	}
}
